<template>
  <div class="p-4">
    <el-card>
      <div class="mb-4 flex justify-between items-center">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索考试名称"
          clearable
          @clear="fetchData"
          @keyup.enter="fetchData"
          style="width: 200px"
        />
        <el-button type="primary" @click="resetSearch">重置</el-button>

        <!-- 新增考试按钮 学生不显示 -->
        <el-button
          v-if="userSystemRole !== 'student'"
          type="primary"
          @click="openAddDialog"
        >
          新增考试
        </el-button>
      </div>

      <el-table :data="examList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="name" label="考试名称" />
        <el-table-column prop="subject" label="所属学科" />
        <el-table-column prop="paperName" label="试卷名称" />
        <el-table-column prop="duration" label="时长(分钟)" width="100" />
        <el-table-column prop="passScore" label="及格分" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)">
              {{ statusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="160"
          v-if="userSystemRole !== 'student'"
        >
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="openEditDialog(row)"
              >编辑</el-button
            >
            <el-button size="small" type="danger" @click="handleDelete(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="mt-4"
        background
        layout="prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="page"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 新增/编辑考试弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑考试' : '新增考试'"
      width="500px"
      v-if="userSystemRole !== 'student'"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="考试名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="试卷名称">
          <el-select v-model="form.paperName" placeholder="请选择试卷">
            <el-option
              v-for="item in paperOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属学科">
          <el-select v-model="form.subject" placeholder="请选择学科">
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="考试时长">
          <el-input-number v-model="form.duration" :min="10" :max="300" /> 分钟
        </el-form-item>
        <el-form-item label="及格分数">
          <el-input-number v-model="form.passScore" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="未发布" value="draft" />
            <el-option label="已发布" value="published" />
            <el-option label="已结束" value="ended" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { getExamList, createExam, updateExam, deleteExam } from "../api/exam";
import { getSubjects } from "../api/subject";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { getPaperLists } from "../api/paper";
import { getUserProfile } from "../api/userProfiles.js";
const router = useRouter();
const userSystemRole = ref(""); // 新增：存角色

const examList = ref([]);
const subjectOptions = ref([]);
const paperOptions = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = 10;
const loading = ref(false);
const searchKeyword = ref("");
const dialogVisible = ref(false);

const defaultForm = {
  id: null,
  name: "",
  subject: "",
  duration: 60,
  passScore: 60,
  status: "draft",
  paperName: "",
};

const form = ref({ ...defaultForm });

async function fetchUserRole() {
  try {
    const res = await getUserProfile(); // 自己的接口
    if (res.code === 200 && res.data) {
      userSystemRole.value = res.data.userSystemRole || "";
    } else {
      userSystemRole.value = "";
    }
  } catch {
    userSystemRole.value = "";
  }
}

// 通用 option 格式处理器
const mapOptions = (data, labelKey, valueKey) =>
  data.map((item) => ({
    label: item[labelKey],
    value: item[valueKey],
  }));

const fetchSubjects = async () => {
  const res = await getSubjects();
  if (res.code === 200) {
    subjectOptions.value = mapOptions(
      res.data,
      "questionsSubject",
      "questionsSubject"
    );
  } else {
    ElMessage.error("获取学科列表失败");
  }
};

const fetchPapers = async () => {
  const res = await getPaperLists();
  if (res.code === 200) {
    paperOptions.value = mapOptions(res.data, "name", "name");
  } else {
    ElMessage.error("获取试卷列表失败");
  }
};

const fetchData = async () => {
  loading.value = true;
  const res = await getExamList({
    page: page.value,
    pageSize,
    keyword: searchKeyword.value,
  });
  loading.value = false;

  if (res.code === 200) {
    examList.value = res.data;
    total.value = res.data.length;
  }
};

const openAddDialog = async () => {
  console.log("打开新增考试弹窗"); // 👈 检查是否打印
  form.value = { ...defaultForm };
  await fetchPapers();
  dialogVisible.value = true;
};

const openEditDialog = async (row) => {
  form.value = { ...row };
  await fetchPapers(); // 👈 编辑也加载一次
  dialogVisible.value = true;
};

const handleSubmit = async () => {
  const res = form.value.id
    ? await updateExam(form.value)
    : await createExam(form.value);
  if (res.code === 200) {
    ElMessage.success("保存成功");
    dialogVisible.value = false;
    fetchData();
  } else {
    ElMessage.error(res.message || "操作失败");
  }
};

const handleDelete = (id) => {
  ElMessageBox.confirm("确定删除该考试吗？", "提示", { type: "warning" })
    .then(async () => {
      const res = await deleteExam(id);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        fetchData();
      } else {
        ElMessage.error(res.message || "删除失败");
      }
    })
    .catch(() => {});
};

const handlePageChange = (newPage) => {
  page.value = newPage;
  fetchData();
};

const resetSearch = () => {
  searchKeyword.value = "";
  fetchData();
};

const statusLabel = (status) =>
  ({ draft: "未发布", published: "已发布", ended: "已结束" }[status] || "未知");

const statusTagType = (status) =>
  ({ draft: "", published: "success", ended: "info" }[status]);

onMounted(() => {
  fetchUserRole();
  fetchSubjects();
  fetchData();
});
</script>
